<template>
  <view class="box">
    <view class="add-info-list">
      <text class="add-info-title">收货人</text>
      <input v-model="form.receiverName" class="add-info-input" placeholder="请输入收货人姓名" />
    </view>

    <view class="add-info-list">
      <text class="add-info-title">手机号码</text>
      <input
        v-model="form.receiverPhone"
        class="add-info-input"
        type="number"
        placeholder="请输入手机号"
      />
    </view>

<view class="add-info-list">
  <text class="add-info-title">所在地区</text>
  <view class="pcc-input-box">
    <input
      v-model="pcc"
      class="add-info-input add-info-input-pcc"
      disabled
      placeholder="请选择地区"
    />
    <view class="map-icon-wrapper" @click.stop="map">
      <uni-icons type="location-filled" size="22" class="map-icon" />
    </view>
  </view>
</view>

    <view class="add-info-list">
      <text class="add-info-title">详细地址</text>
      <textarea
        v-model="form.detailAddress"
        class="add-info-textarea"
        placeholder="请填入详细地址（如：街道名、小区名、门牌号）"
        :maxlength="200"
        :auto-height="true"
      />
    </view>

    <view class="default-box">
      <text>设为默认</text>
      <switch
        class="default-switch"
        :checked="form.isDefault === 1"
        @change="handleDefaultChange"
      />
      <view class="info-message">提醒：下单会优先使用该地址</view>
    </view>

    <view class="add-bar" @tap="save">
      <text class="new-add">{{ isEditing ? '保存修改' : '新增地址' }}</text>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { addAddress,updateAddress ,loadAddresses} from '@/api/Addressapi.js';
import userManager from '@/common/utils/user.js';

// 表单数据（匹配你的结构）
const form = reactive({
  addressId: null,
  userId: userManager.user.userId,
  receiverName: '',
  receiverPhone: '',
  province: '',
  city: '',
  district: '',
  detailAddress: '',
  isDefault: 0 // 0: 否, 1: 是
});

// 省市区拼接显示
const pcc = ref('');

const isEditing =ref(false);

// 页面加载
onLoad((options) => { 
  if (options.address) {	
	isEditing.value = true;  
    try {
      const addr = JSON.parse(decodeURIComponent(options.address));
	  console.log('页面加载的addr:',addr);
      Object.assign(form, addr);
      // 注意：isDefault 在你的数据中是 1/0，不是 true/false
      pcc.value = `${form.province}${form.city}${form.district}`;
    } catch (e) {
      console.error('地址解析失败', e);
      uni.showToast({ title: '地址数据异常', icon: 'none' });
    }
  }
});

// 开关变化
function handleDefaultChange(e) {
  form.isDefault = e.detail.value ? 1 : 0;
  console.log('是否默认地址',form.isDefault);
}

// 跳转地图
function map() {
  uni.navigateTo({
    url: '/pages/address/map/map',
    events: {
      change(data) {
        if (!data) return;
        let temp = data.trim();
        let province = '', city = '', district = '', detail = '';

        // 直辖市列表
        const municipalities = ['北京市', '天津市', '上海市', '重庆市'];
        const isMunicipality = municipalities.some(m => temp.startsWith(m));

        if (isMunicipality) {
          const endIdx = temp.indexOf('市') + 1;
          province = temp.substring(0, endIdx);
          city = province;
          temp = temp.substring(endIdx);
        } else {
          const provEnd = temp.indexOf('省') + 1;
          if (provEnd > 0) {
            province = temp.substring(0, provEnd);
            temp = temp.substring(provEnd);
          }
          const cityEnd = temp.indexOf('市') + 1;
          if (cityEnd > 0) {
            city = temp.substring(0, cityEnd);
            temp = temp.substring(cityEnd);
          }
        }

        // 提取区/县
        const districtEnd = Math.max(
          temp.indexOf('区') + 1,
          temp.indexOf('县') + 1,
          temp.indexOf('市') + 1
        );
        if (districtEnd > 0) {
          district = temp.substring(0, districtEnd);
          detail = temp.substring(districtEnd).trim();
        } else {
          detail = temp;
        }

        form.province = province;
        form.city = city;
        form.district = district;
        form.detailAddress = detail;
        pcc.value = `${province}${city}${district}`;
      }
    }
  });
}

// 保存
async function save() {
  const { receiverName, receiverPhone, province, city, district, detailAddress } = form;

  // 1. 收货人姓名校验
  if (!receiverName?.trim()) {
    uni.showToast({ title: '请输入收货人姓名', icon: 'none' });
    return;
  }

  // 2. 手机号格式校验
  const phoneRegex = /^1[3-9]\d{9}$/;
  if (!receiverPhone) {
    uni.showToast({ title: '请输入手机号', icon: 'none' });
    return;
  }
  if (!phoneRegex.test(receiverPhone)) {
    uni.showToast({ title: '手机号格式不正确', icon: 'none' });
    return;
  }

  // 3. 所在地区校验（省市区必须都存在）
  if (!province || !city || !district) {
    uni.showToast({ title: '请选择完整所在地区', icon: 'none' });
    return;
  }

  // 4. 详细地址校验
  if (!detailAddress?.trim()) {
    uni.showToast({ title: '请输入详细地址', icon: 'none' });
    return;
  }

  // 所有校验通过，开始提交
  const userId = userManager.user.userId;
  try {
    let success = false;
    if (isEditing.value) {
		console.log('保存提交内容：',form);
      success = await updateAddress(userId, form);
    } else {
      success = await addAddress(userId, form);
    }

    if (success) {
      uni.showToast({ title: isEditing.value ? '修改成功' : '新增成功' });
	  // 获取页面栈
	    const pages = getCurrentPages();
	    if (pages.length >= 2) {
	      const prevPage = pages[pages.length - 2]; // 上一页
	      if (typeof prevPage.refreshAddressList === 'function') {
	        await prevPage.refreshAddressList(); // 调用上一页的刷新方法
	      }
	    }
      uni.navigateBack();
	
    } else {
      uni.showToast({ title: '操作失败', icon: 'none' });
    }
  } catch (err) {
    console.error(err);
    uni.showToast({ title: '网络错误', icon: 'none' });
  }
}
</script>

<style scoped>
.box {
  width: 100%;
  padding: 20rpx;
  background-color: white;
  min-height: 100vh;
}

.add-info-list {
  display: flex;
  align-items: center;
  margin-bottom: 40rpx;
  background-color: white;
}

.add-info-title {
  width: 20%;
  font-weight: bold;
  margin-right: 30rpx;
  flex-shrink: 0;
}

.add-info-textarea {
  flex: 1;
  border: 1rpx solid #f0f0f0;
  border-radius: 10rpx;
  padding: 10rpx 15rpx;
  font-size: 32rpx;
  min-height: 80rpx; /* 至少显示两行 */
  line-height: 1.5;
  width: 100%;
  box-sizing: border-box;
  max-height: 120rpx; /* 3 行 */
    overflow-y: auto; /* 超出时可滚动（在部分平台有效） */
}

.add-info-input-pcc {
  flex: 1;
  padding-right: 60rpx; /* 为图标留出右侧空间 */
}

.uni-icons {
  margin-left: 20rpx;
  color: #007aff;
}

.default-box {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-top: 60rpx;
  margin-right: 10rpx;
}

.default-switch {
  transform: scale(0.6);
  margin: 0 20rpx;
}

.info-message {
  color: gray;
  font-size: 28rpx;
  margin-left: 10rpx;
}

.add-bar {
  background-color: red;
  width: 90%;
  position: fixed;
  left: 5%;
  bottom: calc(30rpx + env(safe-area-inset-bottom, 20rpx)); /* 默认 20rpx，安全区额外加 */
  border-radius: 40rpx;
  height: 80rpx;
  display: flex;
  justify-content: center;
  align-items: center;
}

.new-add {
  color: white;
  font-size: 36rpx;
}

/* 所在地区输入框容器 */
.pcc-input-box {
  position: relative;
  flex: 1;
  display: flex;
  align-items: center;
}

.map-icon {
  position: absolute;
  right: 20rpx;
  color: #007aff;
}

.map-icon-wrapper {
  width: 50rpx;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>